﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice_DotNet.Helper
{
    internal static class TextHelper
    {
        /// <summary>
        /// 填充字符串并让文字居中
        /// </summary>
        /// <param name="text">要填充的字符串</param>
        /// <param name="totalWidth">填充总长度</param>
        /// <returns></returns>
        public static string CenterString(string text, int totalWidth)
        {
            if (string.IsNullOrEmpty(text))
                return new string(' ', totalWidth);

            if (text.Length >= totalWidth)
                return text;

            int padding = totalWidth - text.Length;
            int leftPadding = padding / 2;
            int rightPadding = padding - leftPadding;

            return text.PadLeft(leftPadding + text.Length).PadRight(totalWidth);
        }
        public static string ReadPassword()
        {
            string input = "";
            ConsoleKeyInfo key;

            while ((key = Console.ReadKey(true)) != null) // true 表示不回显
            {
                if (key.Key == ConsoleKey.Enter)
                {
                    // 按回车结束输入
                    break;
                }
                else if (key.Key == ConsoleKey.Backspace)
                {
                    // 处理退格键
                    if (input.Length > 0)
                    {
                        input = input.Substring(0, input.Length - 1);
                        // 删除屏幕上显示的 *
                        Console.Write("\b \b"); // 光标后退，空格覆盖，再后退
                    }
                }
                else
                {
                    // 显示 * 而不是明文
                    Console.Write("*");
                    input += key.KeyChar;
                }
            }
            return input;
        }
    }
}
